#!/bin/sh

# Source the SAME settings used by the tivo-monitor.pl script.
CONFIG=/Users/rcrews/bin/tivo/config
if [ -e $CONFIG ]; then
	. $CONFIG
else
	echo "Couldn't load config $CONFIG!";
	exit 1
fi

# Check to see if this script is passed all the proper variables
if [ $# -lt 5 ] || [ $# -gt 5 ]; then
	echo "ERROR: Excepted 5 arguments however $# was provided!"
	exit 1
fi

# Options PASSED to the script from tivo-monitor.pl
FILE=$1
HD=$2
SHOW_NAME=$3
EPISODE_NAME=$4
EPISODE_DESC=$5

OUTPUT_FILENAME=$(basename $FILE | sed 's/\.mpeg/\.m4v/')
OUTPUT_FILE="$ENCODEOUTPUTDIR/$OUTPUT_FILENAME"

echo "Encoding $FILE"
if [ $HD = "No" ]; then
	# Need to deinterlace
	# This is where you will place your encoding tool of choice with your settings you require.
	$ENCODER -i $FILE --cpu 2 -e x264  -q 20.0 -a 1 -E faac -B 160 -6 dpl2 -R 48 -D 0.0 -f mp4 -4 -X 960 --loose-anamorphic -m -x cabac=0:ref=2:me=umh:b-adapt=2:weightb=0:trellis=0:weightp=0 -d slower -o $OUTPUT_FILE
	if [ $? -eq 0 ]; then
		FINISHED=1
	fi
fi
if [ $HD = "Yes" ]; then
	# This is where you will place your encoding tool of choice with your settings you require.
	$ENCODER -i $FILE --cpu 2 -e x264  -q 20.0 -a 1 -E faac -B 160 -6 dpl2 -R 48 -D 0.0 -f mp4 -4 -X 960 --loose-anamorphic -m -x cabac=0:ref=2:me=umh:b-adapt=2:weightb=0:trellis=0:weightp=0 -o $OUTPUT_FILE
	if [ $? -eq 0 ]; then
		FINISHED=1
	fi
fi
# Tag the show if requested. Then also copy to iTunes if requested.
if [ $FINISHED -eq 1 ] && [ $AUTOTAG -eq 1 ]; then
	$TAGGER $OUTPUT_FILE -W --stik "TV Show" --title "$EPISODE_NAME" --TVShowName "$SHOW_NAME" --description "$EPISODE_DESC"
	if [ $? -eq 0 ] && [ $ITUNES -eq 1 ]; then
		$ITUNESCONTROL quit
		sleep 15
		cp "$OUTPUT_FILE" "$ITUNESDROP"
	fi
fi
